﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Phone.Notification;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Navigation;


namespace BuyTrainTicket
{
    class Util
    {
        /// Holds the push channel that is created or found.
        static HttpNotificationChannel pushChannel;
        public static Dispatcher Dispatcher;
        public static NavigationService NavigationService;
        static string name;
        public static string host = "http://42.96.140.114/Buy12306";

        public static void savePushUser(string pname)
        {
            name = pname;
            // The name of our push channel.
            string channelName = "BuyTrainTicketPushChannel";

            // Try to find the push channel.
            pushChannel = HttpNotificationChannel.Find(channelName);

            // If the channel was not found, then create a new connection to the push service.
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

                // Register for this notification only if you need to receive the notifications while your application is running.
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_ShellToastNotificationReceived);

                pushChannel.Open();

                // Bind this new channel for toast events.
                pushChannel.BindToShellToast();

            }
            else
            {
                // The channel was already open, so just register for all the events.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

                // Register for this notification only if you need to receive the notifications while your application is running.
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_ShellToastNotificationReceived);

                // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
                //MessageBox.Show(String.Format("Channel Uri is {0}",
                //    pushChannel.ChannelUri.ToString()));
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Util.host + "/servlet/Buy12306Servlet?action=savepushuser&password=savepushuser&username=" + pushChannel.ChannelUri.ToString() + "&name=;" + name + ";&type=wp8&version=8.1");
                    request.Method = "POST";
                    request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败，请稍后再试1");
                }
            }
        }

        /// <summary>
        /// Event handler for when the push channel Uri is updated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {

            Dispatcher.BeginInvoke(() =>
            {
                // Display the new URI for testing purposes.   Normally, the URI would be passed back to your web service at this point.
                System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
                //MessageBox.Show(String.Format("Channel Uri is {0}",
                //    e.ChannelUri.ToString()));
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Util.host + "/servlet/Buy12306Servlet?action=savepushuser&password=savepushuser&username=" + pushChannel.ChannelUri.ToString() + "&name=;" + name + ";&type=wp8&version=8.1");
                    request.Method = "POST";
                    request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败，请稍后再试1");
                }
            });
        }

        static void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("action=savepushuser");
                postData.Append("&username=" + pushChannel.ChannelUri.ToString());
                postData.Append("&password=savepushuser");
                postData.Append("&type=wp8");
                postData.Append("&version=8.1");
                postData.Append("&name=" + name);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("保存失败，请稍后再试2");
                    
                });
            }
        }

        static void getResponseCallback(IAsyncResult asyncResult)
        {
            try{

                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    JToken isSuccessToken = responseObj.GetValue("isSuccess");
                    JToken errMsgToken = responseObj.GetValue("errMsg");
                    if ((bool)isSuccessToken == true)
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("连接成功,可以正常使用了。");
                            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                        });
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("连接失败。" + (string)errMsgToken);
                        });
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("保存失败，请稍后再试3");

                });
            }

        }

        /// <summary>
        /// Event handler for when a push notification error occurs.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            // Error handling logic for your particular application would be here.
            Dispatcher.BeginInvoke(() =>
                MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
                    e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
                    );
        }

        /// <summary>
        /// Event handler for when a toast notification arrives while your application is running.  
        /// The toast will not display if your application is running so you must add this
        /// event handler if you want to do something with the toast notification.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void PushChannel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
        {
            string message;

            using (StreamReader reader = new StreamReader(e.Notification.Body,Encoding.UTF8))
            {
                message = reader.ReadToEnd();
                JObject respJObject = JsonConvert.DeserializeObject<JObject>(message);
                JToken type = respJObject.GetValue("type");
                if (type != null && ((string)type).Equals("checkcode"))
                {
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/SubmitCheckCode.xaml?msgJson="+message, UriKind.Relative)));
                }
                else if (type != null && ((string)type).Equals("queryleftticket"))
                {
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/TrainList.xaml?msgJson=" + message, UriKind.Relative)));
                }
                else if (type != null && ((string)type).Equals("queryneedpurchase"))
                {
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/QueryOrder.xaml?msgJson=" + message, UriKind.Relative)));
                }
                else if (type != null && ((string)type).Equals("querycontacts"))
                {
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/QueryContact.xaml?msgJson=" + message, UriKind.Relative)));
                }
                else if (type != null && ((string)type).Equals("querycontacts"))
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show((string)respJObject.GetValue("status")));
                }
                else if (type != null && ((string)type).Equals("order"))
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show((string)respJObject.GetValue("status")));
                }
                else if (type != null && ((string)type).Equals("message"))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (JToken msg in (JArray)respJObject.GetValue("message"))
                    {
                        sb.Append((string)((JObject)msg).GetValue("last_msg"));
                        sb.Append("\n");
                    }
                    Dispatcher.BeginInvoke(() => MessageBox.Show(sb.ToString()));
                }
                else
                {
                    // Display a dialog of all the fields in the toast.
                    Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
                }
            }


        }

    }

}
